package com.dousb.cloudlibrary.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dousb.cloudlibrary.common.ErrorCode;
import com.dousb.cloudlibrary.constant.CommonConstant;
import com.dousb.cloudlibrary.exception.ThrowUtils;
import com.dousb.cloudlibrary.mapper.AnnouncementMapper;
import com.dousb.cloudlibrary.model.dto.announcement.AnnouncementQueryRequest;
import com.dousb.cloudlibrary.model.entity.Announcement;
import com.dousb.cloudlibrary.model.enums.AnnouncementStatusEnum;
import com.dousb.cloudlibrary.model.vo.AnnouncementVO;
import com.dousb.cloudlibrary.service.AnnouncementService;
import com.dousb.cloudlibrary.service.UserService;
import com.dousb.cloudlibrary.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 公告表服务实现
 */
@Service
@Slf4j
public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Announcement> implements AnnouncementService {

    @Resource
    private UserService userService;

    @Resource
    private SimpMessagingTemplate simpMessagingTemplate;

    /**
     * 校验数据
     *
     * @param announcement
     * @param add          对创建的数据进行校验
     */
    @Override
    public void validAnnouncement(Announcement announcement, boolean add) {
        ThrowUtils.throwIf(announcement == null, ErrorCode.PARAMS_ERROR);
        //   从对象中取值
        String title = announcement.getTitle();
        String content = announcement.getContent();

        // 创建数据时，参数不能为空
        if (add) {
            //   补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(title), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(StringUtils.isBlank(content), ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        //   补充校验规则
        if (StringUtils.isNotBlank(title)) {
            ThrowUtils.throwIf(title.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(content)) {
            ThrowUtils.throwIf(content.length() > 2000, ErrorCode.PARAMS_ERROR, "内容过长");
        }
    }

    /**
     * 获取查询条件
     *
     * @param announcementQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Announcement> getQueryWrapper(AnnouncementQueryRequest announcementQueryRequest) {
        QueryWrapper<Announcement> queryWrapper = new QueryWrapper<>();
        if (announcementQueryRequest == null) {
            return queryWrapper;
        }
        //   从对象中取值
        Long id = announcementQueryRequest.getId();
        String title = announcementQueryRequest.getTitle();
        String content = announcementQueryRequest.getContent();
        String searchText = announcementQueryRequest.getSearchText();
        String sortField = announcementQueryRequest.getSortField();
        String sortOrder = announcementQueryRequest.getSortOrder();

        //   补充需要的查询条件
        // 从多字段中搜索
        if (StringUtils.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content", searchText));
        }
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取公告表封装
     *
     * @param announcement
     * @param request
     * @return
     */
    @Override
    public AnnouncementVO getAnnouncementVO(Announcement announcement, HttpServletRequest request) {
        if (announcement == null) {
            return null;
        }
        AnnouncementVO announcementVO = new AnnouncementVO();
        BeanUtils.copyProperties(announcement, announcementVO);
        return announcementVO;
    }

    /**
     * 分页获取公告表封装
     *
     * @param announcementPage
     * @param request
     * @return
     */
    @Override
    public Page<AnnouncementVO> getAnnouncementVOPage(Page<Announcement> announcementPage, HttpServletRequest request) {
        List<Announcement> announcementList = announcementPage.getRecords();
        Page<AnnouncementVO> announcementVOPage = new Page<>(announcementPage.getCurrent(), announcementPage.getSize(), announcementPage.getTotal());
        if (CollUtil.isEmpty(announcementList)) {
            return announcementVOPage;
        }
        // 对象列表 => 封装对象列表
        List<AnnouncementVO> announcementVOList = announcementList.stream()
                .map(announcement -> getAnnouncementVO(announcement, request))
                .collect(Collectors.toList());
        announcementVOPage.setRecords(announcementVOList);
        return announcementVOPage;
    }

    /**
     * 是否发布公告
     *
     * @param announcement
     * @return boolean
     * @author 豆沙包
     * @date 2025/10/10 21:17
     */
    @Override
    public boolean publishAnnouncement(Announcement announcement) {
        announcement.setIsActive(AnnouncementStatusEnum.Published.getValue());
        announcement.setCreateTime(new Date());
        if (this.save(announcement)) {
            simpMessagingTemplate.convertAndSend("/topic/announcement", announcement);
            return true;
        }
        return false;
    }

}
